import Dom from '../utils/Dom';
import Utils from '../utils/index';

class Select {
   constructor(el, list, options) {
      this.root = Dom.append(el, 'ul', 'select');
      this.list = list;
      this.userOptions = Utils.extend({
         multiple: false, // 是否可以多选
         selected: 0
      }, options);

      this.value = null;
      this.init();
   }

   init() {
      this.render();
      Dom.addEvent(this.root, 'click', e => {
         if (e.target.tagName === 'LI') {
            let isSelected = e.target.className.indexOf('active') !== -1;
            if (this.userOptions.multiple) {
               if (isSelected) {
                  e.target.className = e.target.className.replace(' active', '');
               } else {
                  e.target.className += ' active';
               }
            } else {
               // 单选操作只允许选中一个，并且不能取消选择
               if (isSelected) {
                  return false;
               }
               this.root.childNodes.forEach(li => {
                  li.className = li.className.replace(' active', '');
               });
               e.target.className += ' active';

            }

            this.setValue(parseInt(e.target.getAttribute('data-index')), isSelected);

         }
         return Dom.nodefault(e);
      });

   }

   render(list) {
      if (list) {
         this.list = list;
      }

      this.value = null;


      let liStr = '';
      if (this.list && this.list.length > 0) {
         this.list.forEach((list, index) => {
            liStr += '<li data-index="' + index + '" ' + (index === this.userOptions.selected ? 'class="active"' : '') + '>' + (typeof list === 'object' ? list.name : list) + '</li>';
         });

         if (this.userOptions.selected !== undefined) {
            this.setValue(this.userOptions.selected)
         }
      }
      this.root.innerHTML = liStr;
   }

   setValue(index, isUnSelected) {
      let current = this.list[index],
         currentValue = current.value || current;
      if (this.userOptions.multiple) {
         if (isUnSelected) {
            this.value = this.value.filter(v => {
               return v !== currentValue;
            });
         } else {
            if (!this.value) {
               this.value = [];
            }
            this.value.push(currentValue);
         }
      } else {
         this.value = currentValue;
      }
   }
}

export default Select;